package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"user/models"
)

type UserController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UserController) Get() {
}
func (c *UserController) Add() {
	name := c.GetString("name")
	tel := c.GetString("tel")
	email := c.GetString("email")
	info, _ := c.GetInt("info")
	get_time := c.GetString("get_time")
	user := models.User{
		Name:    name,
		Tel:     tel,
		Email:   email,
		Info:    info,
		GetTime: get_time,
	}
	err := models.DB.Debug().Create(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *UserController) List() {
	var users []models.User
	err := models.DB.Debug().Find(&users).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: users,
		}
		c.ServeJSON()
	}
}
func (c *UserController) Up() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	tel := c.GetString("tel")
	email := c.GetString("email")
	info, _ := c.GetInt("info")
	get_time := c.GetString("get_time")
	user := models.User{
		Id:      id,
		Name:    name,
		Tel:     tel,
		Email:   email,
		Info:    info,
		GetTime: get_time,
	}
	err := models.DB.Debug().Where("id =?", id).Updates(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *UserController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Where("id =?", id).Delete(&models.User{}).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
